#include <dirent.h>
#include <sys/types.h>
#include <dirent.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include "data.h"
#include "var.h"

static int main_loop(void);
static void prompt(void);
static char *readinput(void);
static int do_cmd(const char *commandline);
extern struct command k_cmd[KMAXSIZE];
//static char commandline[KMAXSIZE];
static char *pcommandline;
extern ENV_VAR* pENV_TABLE;

int main(int argc,char **argv)
{
    init_env_table();
    for (;;) {
        main_loop();
    }
}
int main_loop(void)
{
    prompt();
    pcommandline=readinput();
    int result =  do_cmd(pcommandline);
    if (result == NOFOUND) {
        printf("command not found\n"); 
        if (get_var("PATH")==NULL) {
            printf("You can set a PATH var to make kingshell to find a external command\n");
        }
    }
}
void prompt(void) {
    printf("kingshell>");
    fflush(stdout);
    return ;
}
char *readinput (void)
{
    int i=0;
    int c;
    char * commandline=(char *)malloc(KMAXSIZE);
    while((c=getchar()) != '\n' && i<KMAXSIZE) {
        commandline[i++]=c;
    }
    commandline[i]='\0';
    return commandline;
}

int do_cmd(const char *commandline)
{
    if (commandline == NULL) {
        printf("%s,%s,%d",__FILE__,__FUNCTION__,__LINE__);
        exit (1);
    }
    if (strlen(commandline) == 0)
        return 0;
    /*
     * Analysis commandline if env_var 
     * */
    char *p=NULL;
    if ( (p=strstr(commandline,"=")) != NULL) {
        if ( *(p+1) != ' ' && *(p-1) != ' ') {
            save_env_var(commandline);
            return 0;
        }
    }
    /*
     * built-in command check
     */
    int i=0;
    while (k_cmd[i].cmd != NULL) {
        if (strncmp(commandline,k_cmd[i].name,strlen(commandline))==0) {
            return k_cmd[i].cmd(k_cmd[i].argc,k_cmd[i].argv);
        }
        else
            i++;
    }

    /*
     * PATH var include locations be check.
     */
    {
        const char *p=(const char *)get_var_value(get_var("PATH"));
        if (NULL != p) {
            DIR *dir;
            dir=opendir(p);
            if (dir == NULL) {
                perror("opendir error:");
                exit(1);
            }
            struct dirent * pdirent;
            while((pdirent=readdir(dir)) != NULL) {
                if(strcmp(pdirent->d_name,commandline)==0) {
                    printf ("got command:%s.\n",commandline);
                    return 0;
                }
            }
        }
    }
    return NOFOUND;
}
